package com.weishi.tcp.tool;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Uni {
	/**
	 * gbk编码的字符串转为utf-8编码
	 * @param gbkStr
	 * @return 
	 */
	public static String getUTF8StringFromGBKString(String gbkStr) {  
        try {  
            return new String(getUTF8BytesFromGBKString(gbkStr), "UTF-8");  
        } catch (UnsupportedEncodingException e) {  
            throw new InternalError();  
        }  
    }  
      
	/**
	 * 把GBK编码的字符串转为utf-8编码的byte数组
	 * @param gbkStr
	 * @return
	 */
    public static byte[] getUTF8BytesFromGBKString(String gbkStr) {  
        int n = gbkStr.length();  
        byte[] utfBytes = new byte[3 * n];  
        int k = 0;  
        for (int i = 0; i < n; i++) {  
            int m = gbkStr.charAt(i);  
            if (m < 128 && m >= 0) {  
                utfBytes[k++] = (byte) m;  
                continue;  
            }  
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));  
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));  
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));  
        }  
        if (k < utfBytes.length) {  
            byte[] tmp = new byte[k];  
            System.arraycopy(utfBytes, 0, tmp, 0, k);  
            return tmp;  
        }  
        return utfBytes;  
    }
    
    /**
	 * 从一串字符串中提取所有的IP
	 * @param str
	 * @return
	 */
	public static List<String> getIPbystr(String str){
		List<String> IPs = new ArrayList<String>();
		String regEx="((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		while (m.find()) {
		String result=m.group();
		IPs.add(result);
		}
		return IPs;
	}
	public static void outputStrs(String datas[]) {
		String stadata = "";
		if(datas != null && datas.length>0) {
			for(String data:datas) {
				stadata = stadata+","+data;
			}
			stadata = stadata.substring(1);
			stadata  ="["+stadata +"]";
		}
		System.out.println(stadata);
	}
	public static void outputbytes(byte datas[]) {
		String stadata = "";
		if(datas != null && datas.length>0) {
			for(byte data:datas) {
				stadata = stadata+","+data;
			}
			stadata = stadata.substring(1);
			stadata  ="["+stadata +"]";
		}
		System.out.println(stadata);
	}
	
	public static List<String> CopyList(List<String> list) {
		List<String> rsList = new ArrayList<>();
		for(String str:list) {
			String rsString = new String(str);
			rsList.add(rsString);
		}
		return rsList;
	}
	
	/**
	 * 移除list<String>的第一个匹配的值
	 * @param value
	 * @param list
	 */
	public static void RemoveList(String value,List<String> list) {
		Iterator<String> it = list.iterator();
        while(it.hasNext()){
            String str = (String)it.next();
            if(value.equals(str)){
                it.remove();
                break;
            }        
        }
	}
}
